package org.elip.stewiemaze.server.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.elip.stewiemaze.server.SignedRequestDecoder;
import org.elip.stewiemaze.server.services.PlayerService;
import org.elip.stewiemaze.server.services.RegisterPlayerService;
import org.elip.stewiemaze.server.utils.Constants;
import org.elip.stewiemaze.server.utils.CookieUtils;
import org.elip.stewiemaze.shared.entities.Player;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

/**
 * This servlet handles the initial registration of a facebook user.
 * It stores the current score and the registration form details from the registration page.
 * @author Eli
 *
 */
public class RegisterFacebookPlayerServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doPost(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Logger logger = Logger.getLogger(RegisterFacebookPlayerServlet.class.getName());
		
		logger.fine("Got request from url : " + req.getRequestURL().toString());
		
		handleFacebookRegistration(req,resp);
	
	}
	
	@SuppressWarnings("unchecked")
	private void handleFacebookRegistration(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		Logger logger = Logger.getLogger(RegisterFacebookPlayerServlet.class.getName());
		
		logger.fine("decoding signed_request and getting registration details");
		
		String input = (String)req.getParameter("signed_request").toString();
		
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		try {
			jsonMap = SignedRequestDecoder.parse_signed_request(input, "f493dbd66eb6d4e668f17628ae52c514");
		} catch (Exception e1) {
		}
		
		JSONObject jsonObject = null;
		jsonObject = (JSONObject)jsonMap.get("registration");
		
		String name = "";
		String email = "";
		String userId = "";
		
		try {
			name = (String) jsonObject.get("name");
			email = (String) jsonObject.get("email");
			userId = (String)jsonMap.get("user_id");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		/* retrieve the score from the request */
		Cookie score = CookieUtils.getCookie(req, "tempScore");
		
		/* Register the player to the database, still with no permissions */
		Player player = PlayerService.createFacebookPlayer(name, userId,email, Long.valueOf(score.getValue()));
		RegisterPlayerService.registerPlayer(player);
		
		/* delete this cookie since it is now saved in the database */
		CookieUtils.eraseCookie(req, resp, "tempScore");
		
		/* redirect the user to the application permission section */
		resp.sendRedirect(resp.encodeRedirectURL(Constants.FACEBOOK_AOUTH_URI));	
		
	}

}
